import router from './router'
import store from './store'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router/index'
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  nProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userID) {
        const { roles } = await store.dispatch('user/getUserInfo')
        console.log(roles)
        const newRoutes = asyncRoutes.filter(itm => {
          return roles.menus.some(obj => itm.name === obj)
        })
        router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
        await store.dispatch('permission/permissionRoutes', newRoutes)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  nProgress.done()
})
router.afterEach(route => {
  nProgress.done()
})
